package com.leetcode.LC_MED;

import java.util.HashMap;
import java.util.Map;

public class LC377_2 {
    public int rob(TreeNode root) {
        Map<TreeNode, Integer> map = new HashMap<>();
        return dfs(root, map);
    }

    public int dfs(TreeNode root, Map<TreeNode, Integer> map) {
        if (root == null) {
            return 0;
        }
        if (map.containsKey(root)) {
            return map.get(root);
        }
        int money = root.val;
        if (root.left != null) {
            money += dfs(root.left.left, map) + dfs(root.left.right, map);
        }
        if (root.right != null) {
            money += dfs(root.right.left, map) + dfs(root.right.right, map);
        }
        int res = Math.max(money, dfs(root.left, map) + dfs(root.right, map));
        map.put(root, res);
        return res;
    }
}
